package com.jvm123.api.img.service

import com.jvm123.api.util.Page
import com.jvm123.api.img.entity.Image
import com.jvm123.api.img.repo.ImageRepo
import org.apache.commons.lang3.StringUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service

import javax.annotation.PostConstruct
import javax.annotation.Resource
import javax.validation.constraints.NotNull

/**
 *
 * @author yawn http://jvm123.com
 *     2019/12/18 10:29
 */
@Service
class ImageService {

    static Logger logger = LoggerFactory.getLogger(ImageService.class)

    @Value('${img.source-dir}')
    String sourceDir
    @Value('${img.dest-dir}')
    String destDir
    @Value('${img.url-prefix}')
    String urlPrefix

    @Resource
    ImageRepo imageRepo

    @PostConstruct
    void init() {
        File dir = new File(destDir)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        File sdir = new File(sourceDir)
        if (!sdir.exists()) {
            sdir.mkdirs()
        }
    }

    Page<Image> page(int page, int size) {
        List<Image> list = imageRepo.list((page - 1) * size, size)
        new Page<Image>(page, size, list)
    }

    boolean copy() {
        File source = new File(sourceDir)
        File dest = new File(destDir)
        copyFile(source, dest)
        true
    }

    private void copyFile(File sourceDir, File destDir) {
        File[] list = sourceDir.listFiles()
        for (File file : list) {
            if (file.isDirectory()) {
                copyFile(file, destDir)
            } else {
                String filename = file.getName()
                int index = filename.lastIndexOf(".")
                String name = UUID.randomUUID().toString().replaceAll('-', '')
                String destFileStr = destDir.getAbsolutePath() + File.separator + name + filename.substring(index)
                boolean result = file.renameTo(destFileStr)
                println (name + " " + filename + " " + result)
            }
        }
    }

    boolean sync() {
        String[] dirs = destDir.split(",")
        for (String dirPath : dirs) {
            File dir = new File(dirPath)
            if (dir.isDirectory()) {
                saveDirImages(dir)
            }
        }
        true
    }

    private void saveDirImages(File dir) {
        String dirName = dir.getName()
        for (File imgFile : dir.listFiles()) {

            if ((!imgFile.exists()) || imgFile.isDirectory()) {
                continue
            }

            String imgName = imgFile.getName()
            int index = imgName.lastIndexOf(".")
            String id = imgName.substring(0, index)
            try {
                imageRepo.get(id)
            } catch(Exception ignored) {
                Image image = new Image()
                image.id = id
                image.url = dirName + "/" + imgName
                image.suffix = imgName.substring(index)
                image.date = System.currentTimeMillis()
                image.size = imgFile.length()
                imageRepo.add(image)
                logger.info("saved image info: {}", image)
            }


        }
    }

    boolean update(@NotNull String id, String title, String content) {
        Image img = imageRepo.get(id)
        if (img != null) {
            if(StringUtils.isNotBlank(title)) {
                img.title = title
            }
            if (StringUtils.isNotBlank(content)) {
                img.content = content
            }
            imageRepo.add(img)
        }
        true
    }
}
